#!/usr/bin/env python3
# coding: utf-8

import json
import pdb

from tornado.escape import json_decode, json_encode

from utils.mapspack import mapsprotocol
from utils.constants import RET
from utils.logger import get_logger

logger = get_logger(__name__)


class TCPHandler(object):
    """ request for  TCP Server only"""

    def __init__(self, parse_data, application, **kwargs):
        """
        :param parse_data:
        :param application:
        :param kwargs:
        """
        self.command = str(parse_data.get('command'))
        self.data = parse_data.get('data')
        self.stream = parse_data.get('stream')
        self.application = application
        # self.initialize(**kwargs)
        # self.prepare()
        logger.info("tcphandler init ...")

    def initialize(self, **kwargs):
        """Hook for subclass initialization. Called for each request.

        A dictionary passed as the third argument of a url spec will be
        supplied as keyword arguments to initialize().

        Example::

            class ProfileHandler(RequestHandler):
                def initialize(self, database):
                    self.database = database

                def get(self, username):
                    ...

            app = Application([
                (r'/user/(.*)', ProfileHandler, dict(database=database)),
                ])
        """
        pass

    def prepare(self):
        if not isinstance(self.data, dict):
            body = {
                "reqerr": RET.REQERR,
                "data": {
                    "msg": "it is not dict"
                }
            }
            return self.response(self.stream, body)
        return

    @property
    def settings(self):
        """An alias for `self.application.settings <Application.settings>`."""
        return self.application.settings

    @property
    def redis(self):
        """作为RequestHandler对象的redis属性"""
        return self.application.redis

    @property
    def session(self):
        """作为RequestHandler对象的redis属性"""
        return self.application.session

    async def write(self):
        """把data输入到目标客户端"""
        pass

    def response(self, stream, data):
        """响应数据返回给客户端"""
        ret = mapsprotocol.inpack(json_encode(data))
        stream.write(ret)
